跳到主要内容

JZ67 剪绳子

https://www.nowcoder.com/practice/57d85990ba5b440ab888fc72b0751bf8

这题就是考察数学知识,具体为啥选择 3 看题解吧

import java.util.*;

public class Solution {
// 这题是考察的数学,一般做题记住选择 3 就行了
public int cutRope(int target) {
if (target == 2) return 1;
else if (target == 3) return 2;
// 当n≤3时,只有
// 当n==2时f(x)=1;
// 当n==3时f(x)=2;
if (target % 3 == 0) return (int)Math.pow(3, target / 3);
// 之所以乘 4 是因为原本的多了 1,这里幂再减去 1,这样 1 + 3 就等于 4 了
else if (target % 3 == 1) return 4 * (int)Math.pow(3, target / 3 - 1);
else return 2 * (int)Math.pow(3, target / 3);
}
}